/**
 * 
 */
package org.vsg.common.web.servlet.view;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.AbstractUrlBasedView;

/**
 * @author vison
 *
 */
public class ForwardView extends AbstractUrlBasedView {

	private boolean contextRelative = false;	
	
	public ForwardView(String url) {
		super(url);
	}
	
	public ForwardView(String url,boolean contextRelative) {
		super(url);
		this.contextRelative = contextRelative;
	}	

	
	
	public boolean isContextRelative() {
		return contextRelative;
	}

	public void setContextRelative(boolean contextRelative) {
		this.contextRelative = contextRelative;
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.view.AbstractView#renderMergedOutputModel(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void renderMergedOutputModel(Map<String, Object> arg0,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		// Prepare target URL.
		StringBuilder targetUrl = new StringBuilder();
		if (this.contextRelative && getUrl().startsWith("/")) {
			// Do not apply context path to relative URLs.
			targetUrl.append(request.getContextPath());
		}
		targetUrl.append(getUrl());
		
		// --- forward the new url ---
		forward(request ,response , targetUrl.toString() );
	
	}
	
	protected void forward(HttpServletRequest request, HttpServletResponse response, String targetUrl) throws IOException , ServletException {
		RequestDispatcher rd = request.getRequestDispatcher(targetUrl);
		if (rd == null) {
			throw new ServletException(
					"Could not get RequestDispatcher for [" + getUrl() + "]: check that this file exists within your WAR");
		}	
		
		if (logger.isDebugEnabled()) {
			logger.debug("Forwarding to resource [" + getUrl() + "] in InternalResourceView '" + getBeanName() + "'");
		}
		rd.forward(request, response);		
	}	
	
}
